package uestc.lj.basic.tree;

/**
 * 在二叉树中寻找一个节点的后继节点
 *
 * @Author:Crazlee
 * @Date:2021/11/23
 */
public class Code10_findSuccessorNode {
	public static class Node {
		public int value;
		public Node left;
		public Node right;
		//指向其父节点的指针
		public Node parent;

		public Node(int data) {
			this.value = data;
		}
	}

	public static Node getSuccessorNode(Node node) {
		if (node == null) {
			return node;
		}
		if (node.right != null) {
			return getMostLeft(node.right);
		} else {//当前节点没有右子树
			Node parent = node.parent;
			//找当前节点是其父节点的左孩子或者整棵树没有左孩子
			while (parent != null && parent.left != node) {
				node = parent;
				parent = node.parent;
			}
			return parent;
		}
	}

	/**
	 * 寻找一棵树的最左边节点
	 *
	 * @param node 数
	 * @return 最左边节点
	 */
	private static Node getMostLeft(Node node) {
		if (node == null) {
			return node;
		}
		while (node.left != null) {
			node = node.left;
		}
		return node;
	}
}
